package com.loadmore.common.web

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.webkit.*
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.loadmore.common.R
import com.loadmore.common.base.BaseActivity
import com.loadmore.common.model.MessageEvent
import com.loadmore.common.router.RouterPath
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.activity_web.*
import org.json.JSONObject


@Route(path = RouterPath.Web)
class WebActivity : BaseActivity() {
    public var url: String?= null
    public var html:String? = null
    @SuppressLint("JavascriptInterface")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web)
        setRefreshEnable(true)
        url = intent.getStringExtra("url")
        html = intent.getStringExtra("html")
        var webSettings = webview.settings
        webSettings.javaScriptEnabled = true
        webSettings.setSupportZoom(false)
        webSettings.javaScriptCanOpenWindowsAutomatically = true

        webSettings.useWideViewPort = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSettings.loadWithOverviewMode = true
        webview.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                //actionBar.setCenterTitle(title)
            }

            override fun onCloseWindow(window: WebView?) {
                super.onCloseWindow(window)
            }

            override fun onJsPrompt(view: WebView?, url: String?, message: String?, defaultValue: String?, result: JsPromptResult?): Boolean {
                return super.onJsPrompt(view, url, message, defaultValue, result)
            }

            override fun onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt()
            }

            override fun onGeolocationPermissionsShowPrompt(origin: String?, callback: GeolocationPermissions.Callback?) {
                super.onGeolocationPermissionsShowPrompt(origin, callback)
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
            }

            override fun onReceivedIcon(view: WebView?, icon: Bitmap?) {
                super.onReceivedIcon(view, icon)
            }

            override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
                return true
            }
        }
        webview.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                return super.shouldOverrideUrlLoading(view, request)
            }


        }
        webview.addJavascriptInterface(JavaScriptCallback(),"message")

        if (!TextUtils.isEmpty(url)) {
            webview.loadUrl(url)
        }
        if (!TextUtils.isEmpty(html)) {
            webview.loadData(html,"text/html;charset=UTF-8",null)
        }


        actionBar.setNavigationOnClickListener {
            if (goBack()) {
                return@setNavigationOnClickListener
            }
            finish()
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        super.onRefresh(refreshLayout)
        webview.loadUrl(url)
        refreshLayout.finishRefresh(2000)
    }


    inner class JavaScriptCallback{
        /**
         * 扫描二维码
         */
        @JavascriptInterface
        public fun scan() {
            ARouter.getInstance().build(RouterPath.QRCode).withBoolean("web",true).navigation()

        }

        @JavascriptInterface
        public fun getCurrentLocation() {
            val params = HashMap<String,String>()
            params.put("error","0")
            params.put("latitude","123.456789")
            params.put("longitude","98.456789")
            runOnUiThread {
                webview.loadUrl("javascript:getCurrentLocation("+JSONObject(params).toString()+")")
            }
        }
    }
    override fun onBackPressed() {
        if(goBack()) {
            return
        }
        super.onBackPressed()
    }

    override fun onMessageEvent(event: MessageEvent) {
        super.onMessageEvent(event)
        val str = event.data.toString()
        val m = hashMapOf<String,String>()
        m.put("result",str)
        runOnUiThread {
            webview.loadUrl("javascript:scan("+JSONObject(m)+")")
        }
    }

    public fun goBack(): Boolean {
        if(webview.canGoBack()) {
            webview.goBack()
            return true
        }
        return false
    }
}
